package org.dahuatech.ssh.dao.account;

import java.util.List;

import org.dahuatech.ssh.common.orm.hibernate.HibernateDao;
import org.dahuatech.ssh.entity.account.Authority;
import org.dahuatech.ssh.entity.account.Role;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;


/**
 * 授权对象的泛型DAO.
 * 
 * @author calvin
 */
@Component
public class AuthorityDao extends HibernateDao<Authority, Long> {
    
    private static final String QUERY_ROLE_BY_AUTHORITYID = "select r from Role r left join r.authorities a where a.id=?";
    
    @SuppressWarnings("unchecked")
    public List<Authority> listAllAuthorities(){
        String hql="from Authority authority order by authority.pId,authority.id";
        return this.createQuery(hql).list();
    }
    
    @SuppressWarnings("unchecked")
    public List<Authority> listAllAuthorities(Long userid){
        String hql="from Authority authority " +
                "join authority.roles roles " +
                "join roles.users users where users.id=? order by authority.pId,authority.id";
        return this.createQuery(hql, userid).list();
    }
    
    /**
     * 
     * listAuthoritiesByIds:(按Id获取权限对象)
     *
     * @param ids
     * @return      
     * @throws
     * @since  Ver 3.0
     */
    public List<Authority> listAuthoritiesByIds(List<Long> ids){
        return this.get(ids);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void delete(Long id) {
        Authority authority=get(id);
        List<Role> roleList=createQuery(QUERY_ROLE_BY_AUTHORITYID, authority.getId()).list();
        for(Role r:roleList){
            r.getAuthorities().remove(authority);
        }
        super.delete(id);
        
    }
    
    
    
}
